//
//  UIImage + Ext.swift
//  WeiboSwift
//
//  Created by xiaokui wu on 9/12/16.
//  Copyright © 2016 wxk. All rights reserved.
//

import UIKit

extension UIImage
{
    func imageWithNonInterpolatedFromCIImage(image: CoreImage.CIImage, size: CGFloat) -> UIImage {
        let extent = CGRectIntegral(image.extent)
        let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
        
        // 创建bitmap
        let width = CGRectGetWidth(extent) * scale
        let height = CGRectGetHeight(extent) * scale
        let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
        let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage = context.createCGImage(image, fromRect: extent)
        
        CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None)
        CGContextScaleCTM(bitmapRef, scale, scale)
        CGContextDrawImage(bitmapRef, extent, bitmapImage)
        
        //保存bitmap图片
        let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
    
        return UIImage(CGImage: scaledImage)
    }
}
